package com.jumlabs.presentation.backend.web.catalogs.auth;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jumlabs.entities.auth.Group;
import com.jumlabs.entities.auth.User;
import com.jumlabs.services.auth.UserService;
import com.jumlabs.services.auth.GroupService;

@Controller
@RequestMapping(value = "/usuarios")
public class UserController {
	private static final Logger logger = LoggerFactory
			.getLogger(UserController.class);
	@Autowired
	private UserService userService;
	@Autowired
	GroupService groupService;

	@RequestMapping(method = RequestMethod.GET)
	public String list(Model model) {
		return "users";
	}

	@RequestMapping(method = RequestMethod.GET, value = "/crear")
	public String create(Model model) {
		model.addAttribute(new User());
		model.addAttribute("groups", groupService.findAll());
		return "user_create";
	}

	@RequestMapping(value = "/crear", method = RequestMethod.POST)
	public @ResponseBody
	Map<String, ? extends Object> create(@RequestBody Map<String, ? extends Object> requestUser) {
		User user = new User();
		user.setUserName(requestUser.get("userName").toString());
		user.setPassword(requestUser.get("password").toString());
		Set<Group> groupList=new HashSet<Group>();
		if(requestUser.get("groups") instanceof Iterable){
			Iterable iterable = (Iterable) requestUser.get("groups");
			groupList = getGroupListFromIterableIds(iterable);
		}
		else{
			try{
				Integer groupID=Integer.parseInt(requestUser.get("groups").toString());
				Group group=groupService.findOne(groupID);
				groupList.add(group);
			}
			catch(Exception e){}
		}
		user.setGroups(groupList);
		userService.save(user);
		return Collections.singletonMap("id", "");
	}

	private Set<Group> getGroupListFromIterableIds(Iterable iterable) {
		Set<Group> groups = new HashSet<Group>();
		List<Integer> groupsIds = new ArrayList<Integer>();
		for (Object oId : iterable) {
			try {
				groupsIds.add(Integer.parseInt(oId.toString()));

			} catch (Exception e) {
			}
		}
		if (groupsIds.size() > 0) {
			Iterable<Group> groupsIt = groupService.findAll(groupsIds);
			for (Group group : groupsIt) {
				groups.add(group);
			}
		}
		return groups;
	}

	@RequestMapping(value = "/{username}",params="type=json", method = RequestMethod.GET)
	public @ResponseBody
	User getJSONUser(@PathVariable String username) {
		User usuario = userService.findUserByUserName(username);
		if (usuario == null) {
		}
		return usuario;
	}

	@RequestMapping(params="type=json")
	public @ResponseBody
	Collection<User> getUsersJSON() {
		return userService.getUsers();
	}

	
	@RequestMapping(params={"type=json","paginated=true"}, method = RequestMethod.GET)
	public @ResponseBody
	Map<Object, Object> getJSONUsersWithPaginationInfo(
			@RequestParam int iDisplayLength, @RequestParam int iDisplayStart,
			int sEcho) {
		int page = com.jumlabs.util.data.Pagination.calcPage(iDisplayStart,iDisplayLength);
		Page<User> userPage = userService.getUsersPaginated(page,
				iDisplayLength);		
		Map<Object, Object> result = com.jumlabs.util.data.Pagination.getDataTablesFormattedMap(iDisplayStart, iDisplayLength, sEcho, userPage);
		return result;
	}
	

	@RequestMapping(value = "/validate_repeated_user")
	public @ResponseBody
	Map<String, Boolean> validateRepeatedUser(@RequestParam String userName) {
		return Collections.singletonMap("exists", userService.exists(userName));
	}

}
